// 配置API接口地址
var root = process.env.VUE_APP_API;
var root1 = process.env.VUE_APP_API1;
var Main = process.env.VUE_APP_MAIN;
var url = window.location.href;
console.log(url, root1, root)
if (url.indexOf('http://d-h5.udui.com/') >= 0 || url.indexOf('https://h5.udui.com/') >= 0){
  root1 = process.env.VUE_APP_API2;
  root = process.env.VUE_APP_API2;
  console.log(url,root1, root)
}
// 引用axios
var axios = require("axios");
import qs from "qs";

// // 添加请求拦截器
let configs="";
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    configs = config;
    // console.log(22,config);
    return config;

  }, function (error) {
    // console.log(33, error);
    // 对请求错误做些什么
    return Promise.reject(error);
  });


// // 添加响应拦截器
// axios.interceptors.response.use(function (response) {
//     // 对响应数据做点什么
//     console.log(11,response);
//     if (response.request.responseURL.indexOf("h5.daxiongdaikuan.com")!=-1) {
//       // console.log(response.request.responseURL.split("http://h5.daxiongdaikuan.com/"));
//       // "http://h5.daxiongdaikuan.com/";
//       // let url = Main + "#/HomeBefore" + response.request.responseURL.split("http://h5.daxiongdaikuan.com/")[1];
//       // console.log(url)
//       // window.location.href = url;
//     }
//   return response;
// }, function (error) {
//    console.log(44,error);
//     console.log(Promise.reject(error));
//   // 对响应错误做点什么
//   return Promise.reject(error);
// });
// axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";


  // application/json
// 自定义判断元素类型JS
function toType(obj) {
  return {}.toString
    .call(obj)
    .match(/\s([a-zA-Z]+)/)[1]
    .toLowerCase();
}
// 参数过滤函数
function filterNull(o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key];
    }
    if (toType(o[key]) === "string") {
      o[key] = o[key].trim();
    } else if (toType(o[key]) === "object") {
      o[key] = filterNull(o[key]);
    } else if (toType(o[key]) === "array") {
      o[key] = filterNull(o[key]);
    }
  }
  return o;
}

function formData(data) {
  let formData = new FormData();

  // let formData = new URLSearchParams();
  let isEmptyObject = true;
  for (let k in data) {
    isEmptyObject = false;
    formData.append(k, data[k]);
  }
  if (isEmptyObject) {
    formData = "";
  }
  return formData;

}
function apiAxios(method, url, params, success, failure, header, baseURL,catchfc) {
  // var  baseURL = 'http://192.168.0.123:7081'
  if (params) {
    params = filterNull(params);
      // params = formData(params);
  }
  axios({
    method: method,
    url: url,
    // data: null,
    data: method === "POST" || method === "PUT" ? params : null,
    baseURL: baseURL||root,
    headers: header ? header : null,
    timeout: 10000,
    // withCredentials: false,
    // maxRedirects: 0,
    validateStatus: function(status) {
      return status >= 200 && status < 500; // 状态码在大于或等于500时才会 reject
    }
  })
    .then(function(res) {
      if (res.data.success === true) {
        if (success) {
          success(res.data);
        }
      } else {
        if (failure) {
          failure(res.data);
        }
      }
    })
    .catch(function(err) {
      if(catchfc){
        catchfc(err);
      }else{
        let res = err.response;
         console.log(err);
        if (err.response) {
          // 请求已发出，但服务器响应的状态码不在 2xx 范围内
          console.log(err.response.data);
          console.log(err.response.status);
          console.log(err.response.headers);
        } else {
          console.log("Error", err.message);
        }
        console.log(err.config);
      }

      // var username = document.createElement("textarea");
      // username.value = JSON.stringify(configs);
      // document.body.innerHTML = '';
      // document.body.appendChild(username);

      // username.style.width = "100%";
      // username.style.height = "100%";
      // username.style.fontSize="14px";
      console.log(err);
      if (err) {
        if (failure) {
          failure({ errorMessage: "网络异常，请稍后再试" });
        }
      }
    });
}
function apiAxios1(method, url, params, success, failure, header, baseURL,catchfc) {
  // var  baseURL = 'http://192.168.0.123:7081'
  if (params) {
    params = filterNull(params);
      // params = formData(params);
  }
  console.log(root1);
  axios({
    method: method,
    url: url,
    // data: null,
    data: method === "POST" || method === "PUT" ? params : null,
    baseURL: baseURL||root1,
    headers: header ? header : null,
    timeout: 10000,
    // withCredentials: false,
    // maxRedirects: 0,
    validateStatus: function(status) {
      return status >= 200 && status < 500; // 状态码在大于或等于500时才会 reject
    }
  })
    .then(function(res) {
      if (res.data.success === true) {
        if (success) {
          success(res.data);
        }
      } else {
        if (failure) {
          failure(res.data);
        }
      }
    })
    .catch(function(err) {
      if(catchfc){
        catchfc(err);
      }else{
        let res = err.response;
         console.log(err);
        if (err.response) {
          // 请求已发出，但服务器响应的状态码不在 2xx 范围内
          console.log(err.response.data);
          console.log(err.response.status);
          console.log(err.response.headers);
        } else {
          console.log("Error", err.message);
        }
        console.log(err.config);
      }

      // var username = document.createElement("textarea");
      // username.value = JSON.stringify(configs);
      // document.body.innerHTML = '';
      // document.body.appendChild(username);

      // username.style.width = "100%";
      // username.style.height = "100%";
      // username.style.fontSize="14px";
      console.log(err);
      if (err) {
        if (failure) {
          failure({ errorMessage: "网络异常，请稍后再试" });
        }
      }
    });
}


// 返回在vue模板中的调用接口
export default {
  get: function(url, params, success, failure, header) {
    return apiAxios("GET", url, params, success, failure, header);
  },
  get1: function(url, params, success, failure, header) {
    return apiAxios1("GET", url, params, success, failure, header);
  },
  post: function(url, params, success, failure, header) {
    return apiAxios("POST", url, params, success, failure, header);
  },
  post1: function(url, params, success, failure, header) {
    return apiAxios1("POST", url, params, success, failure, header);
  },
  put: function(url, params, success, failure, header) {
    return apiAxios("PUT", url, params, success, failure, header);
  },
  delete: function(url, params, success, failure, header) {
    return apiAxios("DELETE", url, params, success, failure, header);
  }
};
